#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "func.h"
#include "proto.h"

#define	BUFSZ 	(16384)

void	w2f(const char *fname, uint8_t *in, int len)
{
	FILE	*fp;

	fp = fopen(fname, "w");
	if(fp)
	{
		fwrite(in, 1, len, fp);
		fclose(fp);
	}
}

void	gen_warn(FILE *fp)
{
	fprintf(fp, "/*\n"); 
	fprintf(fp, " *\tWARN  :  THIS BACKEND CODE IS AUTO GENERATE, ALL RIGHTS RESERVED.\n");
	fprintf(fp, " *\tAUTHOR:  ZhaoChunPing\n");
	fprintf(fp, " *\tEMAIL :  forxy@126.com\n");
	fprintf(fp, " *\tDATE  :  2022.1\n");
	fprintf(fp, " */\n\n");

	fprintf(fp, "#include <stdint.h>\n");
	fprintf(fp, "#include <stdlib.h>\n");
	fprintf(fp, "#include \"pkcs11.h\"\n");
	fprintf(fp, "#include \"msg_fmt.h\"\n");
	fprintf(fp, "#include \"auto_inner_pkcs11.h\"\n");
	fprintf(fp, "\n");

	fflush(fp);
}

int	main(int argc, char *argv[])
{
	int	num, i, len = 0, ret;
	char	*str;
	FILE	*fp;
	func_t *out, *cur;

	if(argc != 3)
	{
		printf("usage: gen_backend func.proto out.c\n");
		return -1;
	}

	str = malloc(BUFSZ);
	memset(str, 0, BUFSZ);

	ret = proto_load(argv[1], &out, &num);
	if(ret != 0) {
		printf("proto_load %s failed.\n", argv[1]);
		return -1;
	}
	fp = fopen(argv[2], "w");
	if(fp == NULL) {
		printf("open %s failed.\n", argv[2]);
		return -1;
	}
	gen_warn(fp);

	for(i = 0; i < num; i++)
	{
		cur = out + i;
		memset(str, 0, BUFSZ);
		func_gen_backend(cur, str);
		len += strlen(str);
		fprintf(fp, "%s\n\n", str);
		fflush(fp);
	}
	fclose(fp);
	return 0;
}
